import { observer } from 'mobx-react'
import './managementOperations.less'
import { useEffect, useRef, useState } from 'react'
import { ActionType } from '@ant-design/pro-components'
import { Button, Popconfirm, Form, Input, Select, Space, Table, DatePicker, message, Badge } from 'antd'
import type { PopconfirmProps } from 'antd'
import { useNavigate } from 'react-router-dom'
import { ReloadOutlined, SearchOutlined } from '@ant-design/icons'
import { ColumnsType } from 'antd/es/table'
import { getManagementOperationsList } from '@/apis/logManagement/managementOperations'
const { Option } = Select
const { RangePicker } = DatePicker

interface DataType {
  id: string
  key: string
  serialNumber: number
  productName: string
  platform: string
  version: string
  status: string
  updateDescription: string
  downloadUrl: string
  operator: string
  operationTime: string
}
// 定义筛选表单的接口
interface FilterForm {
  startTime: string
  endTime: string
  operationUser: string
  dateRange: [string, string] | null
}

const StaffManagement: React.FC = () => {
  // 初始化表单状态
  const initialFilterForm: FilterForm = {
    startTime: '',
    endTime: '',
    operationUser: '',
    dateRange: ['', '']
  }
  const navigate = useNavigate()

  const [data, setData] = useState<DataType[]>([])
  const [loading, setLoading] = useState(false)

  const [searchForm, setSearchForm] = useState<FilterForm>(initialFilterForm)

  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  })

  const getData = async (params = {}) => {
    try {
      setLoading(true)
      const response = await getManagementOperationsList({
        ...searchForm,
        current: pagination.current,
        pageSize: pagination.pageSize,
        ...params
      })
      if (response.code === 200) {
        // 为每条数据添加唯一的 key
        const listWithKeys = response.data.list.map((item: any) => ({
          ...item,
          key: item.id
        }))
        setData(listWithKeys)
        setPagination(prev => ({
          ...prev,
          total: response.data.total
        }))
      } else {
        message.error(response.message || '获取数据失败')
      }
    } catch (error) {
      console.log(error)
      message.error('获取数据失败')
    } finally {
      setLoading(false)
    }
  }
  // 搜索事件处理
  const handleSearch = async () => {
    try {
      const { dateRange, ...rest } = searchForm
      const params = {
        ...rest,
        current: 1,
        pageSize: pagination.pageSize,
        startTime: dateRange?.[0] || undefined,
        endTime: dateRange?.[1] || undefined
      }

      setPagination(prev => ({ ...prev, current: 1 }))
      await getData(params)
    } catch (error) {
      console.error('查询失败:', error)
      message.error('查询失败')
    }
  }
  /**
   * 重置表单
   */
  const resetSearchForm = () => {
    setSearchForm(initialFilterForm)
    setPagination(prev => ({ ...prev, current: 1 }))
    getData({
      ...initialFilterForm,
      current: 1,
      pageSize: pagination.pageSize
    })
  }
  const handleTableChange = (newPagination: any) => {
    setPagination(prev => ({
      ...prev,
      current: newPagination.current,
      pageSize: newPagination.pageSize
    }))
    getData({
      current: newPagination.current,
      pageSize: newPagination.pageSize
    })
  }

  const handleDetails = (id: any) => {
    navigate(`/setting/logManagement/managementOperations/details/${id}`)
  }

  const columns: ColumnsType<DataType> = [
    {
      title: '序号',
      dataIndex: 'id',
      key: 'id',
      render: (text: any, record: any, index: number) => {
        // 计算序号，分页时会自动显示正确的序号
        return (pagination.current - 1) * pagination.pageSize + (index + 1)
      }
    },
    {
      title: '操作时间',
      dataIndex: 'operationTime',
      key: 'operationTime'
    },
    {
      title: '操作人',
      dataIndex: 'operator',
      key: 'operator'
    },
    {
      title: '操作状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: number) => (
        <>
          <Badge
            status={['error', 'success'][status] as any}
            styles={{ indicator: { marginRight: '8px' } }}
          />
          {['失败', '成功'][status]}
        </>
      )
    },
    {
      title: '操作模块',
      dataIndex: 'module',
      key: 'module'
    },
    {
      title: '操作内容',
      dataIndex: 'content',
      key: 'content'
    },
    {
      title: '操作IP',
      dataIndex: 'ip',
      key: 'ip'
    },
    {
      title: '操作',
      key: 'ip',
      width: 120,
      fixed: 'right',
      render: (item, e) => (
        <div className='table-cell-actions'>
          <Button type="link" onClick={() => handleDetails(e.id)}>详情</Button>
          <Popconfirm
            title="提示"
            description="是否删除？"
            onConfirm={confirm}
            onCancel={cancel}
            okText="是的"
            cancelText="取消"
          >
            <Button type="link">删除</Button>
          </Popconfirm>
        </div>
      )
    }
  ]
  const confirm: PopconfirmProps['onConfirm'] = (e) => {
    console.log(e)
    message.success('点击确定')
  }
  const cancel: PopconfirmProps['onCancel'] = (e) => {
    console.log(e)
    message.error('点击取消')
  }
  const handleRefresh = () => {
    message.success('刷新完成')
  }
  // 页面初始化时获取数据
  useEffect(() => {
    getData()
  }, [])
  return (
    <div className="app-container">
      <div className="filterForm">
        <Form variant={'filled'} layout="inline" className="form">
          <Form.Item name="操作时间" label="操作时间">
            <RangePicker />
          </Form.Item>
          <Form.Item name="操作人" label="操作人">
            <Input />
          </Form.Item>
          <Form.Item name="操作" label="操作">
            <Input />
          </Form.Item>
          <Form.Item name="筛选方式" label="筛选方式">
            <Select placeholder="请选择筛选方式" allowClear>
              <Option value="">male</Option>
              <Option value="female">female</Option>
              <Option value="other">other</Option>
            </Select>
          </Form.Item>
          <Form.Item name="筛选方式" label="筛选方式">
            <Select placeholder="请选择筛选方式" allowClear>
              <Option value="">male</Option>
              <Option value="female">female</Option>
              <Option value="other">other</Option>
            </Select>
          </Form.Item>
        </Form>
        <div className="rightAction">
          <Button type="primary" htmlType="submit" onClick={handleSearch}>
            <SearchOutlined />
            查询
          </Button>
          <Button onClick={resetSearchForm}>
            <ReloadOutlined />
            重置
          </Button>
        </div>
      </div>
      <div className="table-operations">
        <Button onClick={handleRefresh}>刷新</Button>
      </div>
      <Table
        columns={columns}
        dataSource={data}
        pagination={{
          ...pagination,
          showSizeChanger: true,
          showTotal: total => `共 ${total} 条`
        }}
        onChange={handleTableChange}
        tableLayout="fixed"
        scroll={{ x: 1200 }}
        loading={loading}
      />
    </div>
  )
}

export default observer(StaffManagement)
